package com.weathereport.ws;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.widget.Toast;

import com.weathereport.R;
import com.weathereport.entity.Local;
import com.weathereport.entity.Forecast;

public class WeatherWS {
	
	private HttpEntity connectWS(Context ctx, Local local){
		
		HttpClient httpclient = new DefaultHttpClient();
		
		SharedPreferences settings = ctx.getSharedPreferences("prefs", ctx.MODE_PRIVATE);
        
        String authorization = settings.getString("authorizationWeather", null);        
		
        String url = "http://api.wunderground.com/api/" + authorization + 
        		"/conditions/forecast10day/lang:BR/q/";
                
    	url = url + local.getLatitude().toString() + ","+ local.getLongitude().toString() + ".json";        
        
        HttpGet httpget = new HttpGet(url);
	    HttpResponse response;
	    HttpEntity entity = null;
	    
	    try {
	        response = httpclient.execute(httpget);
	
	        entity = response.getEntity();
	
	    } catch (ClientProtocolException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    
	    return entity;
	}
	
	
	public List<Forecast> getForecast(Context ctx, Local local){
		
		HttpEntity entity = connectWS(ctx, local);
		
		List<Forecast> forecast10;
		
		if (entity != null){
			
			forecast10 = new ArrayList<Forecast>();
			
			// A Simple JSON Response Read
	        InputStream instream;
			try {
				instream = entity.getContent();
				String result = convertStreamToString(instream);
				instream.close();
				
				
				JSONObject json = new JSONObject(result);
				
				JSONObject jsonCurrentObservation = json.getJSONObject("current_observation");
				
		        JSONObject jsonForecast = json.getJSONObject("forecast");		        
		        JSONObject jsonSimpleForecast = jsonForecast.getJSONObject("simpleforecast");		        
		        JSONArray jsonArraySimpleForecast = jsonSimpleForecast.getJSONArray("forecastday");
			        
		        for (int i = 0; i < jsonArraySimpleForecast.length(); i++) {
		        	Forecast forecast = new Forecast();
		        	
		        	JSONObject day = jsonArraySimpleForecast.getJSONObject(i);
					JSONObject date = day.getJSONObject("date");					
					
					forecast.setDay(date.getString("day") + "/" + date.getString("month") + "/" + date.getString("year"));
					
					if (i == 0){
						
						forecast.setTempNow(jsonCurrentObservation.getString("temp_c"));
						forecast.setWindNow(jsonCurrentObservation.getString("wind_kph"));
						forecast.setHumidityNow(jsonCurrentObservation.getString("relative_humidity"));
						forecast.setRainNow(jsonCurrentObservation.getString("precip_today_metric"));
					}
					
					forecast.setHighTemp(day.getJSONObject("high").getString("celsius"));
					forecast.setLowTemp(day.getJSONObject("low").getString("celsius"));
					forecast.setWeather(day.getString("conditions"));
					forecast.setRain(day.getJSONObject("qpf_allday").getString("mm"));
					forecast.setSnow(day.getJSONObject("snow_allday").getString("cm"));
					forecast.setWind(day.getJSONObject("avewind").getString("kph"));
					forecast.setHumidity(day.getString("avehumidity"));
					
					forecast10.add(forecast);
				}
		        
		        
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
		}else {
			forecast10 = null;
		}
		return forecast10;
	}
	
	private static String convertStreamToString(InputStream is) {

        /*BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
 
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }*/
		
		
		BufferedReader reader;
		StringBuilder sb = new StringBuilder();
		String line = null;
		try {
			reader = new BufferedReader(new InputStreamReader(is), 8);
			
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
        return sb.toString();
    }
}
